<!-- V-webapp/src/views/HomeView.vue -->
<template>
  <div class="home-page">
    <!-- 顶部搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索活动或商品..."
        class="search-input"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <!-- 轮播图 -->
    <el-carousel height="160px" class="banner" indicator-position="outside">
      <el-carousel-item v-for="item in banners" :key="item.id">
        <img :src="item.image" class="carousel-image" alt="轮播图" />
      </el-carousel-item>
    </el-carousel>

    <!-- 活动列表 -->
    <div class="section">
      <div class="section-header">
        <h3>推荐活动</h3>
        <span class="more" @click="$router.push('/activities')">更多</span>
      </div>
      
      <div class="activities-grid" v-if="!loading && activities.length > 0">
        <div 
          v-for="activity in activities" 
          :key="activity.activity_id"
          class="activity-card"
          @click="$router.push(`/activity/${activity.activity_id}`)"
        >
          <!-- 使用动态图片 -->
          <img
            :src="getActivityImage(activity.cover_image)"
            class="activity-cover"
            alt="活动封面"
          />
          <div class="activity-info">
            <div class="activity-title">{{ activity.title }}</div>
            <div class="activity-author">{{ activity.anchor?.anchor_name || '未知主播' }}</div>
            <div class="activity-meta">
              <span class="activity-time">{{ formatTime(activity.start_time) }}</span>
              <span class="activity-status" :class="`status-${getStatusType(activity.status)}`">
                {{ getStatusText(activity.status) }}
              </span>
            </div>
          </div>
        </div>
      </div>
      <div v-else-if="!loading" class="empty-state">
        暂无活动
      </div>
      <div class="loading-state" v-else>
        <el-icon class="is-loading"><Loading /></el-icon>
        <p>加载中...</p>
      </div>
    </div>

    <!-- 商品推荐 -->
    <div class="section">
      <div class="section-header">
        <h3>热门商品</h3>
        <span class="more" @click="$router.push('/products')">更多</span>
      </div>
      
      <div class="products-grid" v-if="!loading && products.length > 0">
        <div 
          v-for="product in products" 
          :key="product.id"
          class="product-card"
          @click="$router.push(`/product/${product.id}`)"
        >
          <img
            :src="getProductImage(product.cover_image)"
            class="product-image"
            alt="商品图片"
          />
          <div class="product-info">
            <div class="product-name">{{ product.name }}</div>
            <div class="product-price">¥{{ product.price }}</div>
          </div>
        </div>
      </div>
      <div v-else-if="!loading" class="empty-state">
        暂无商品
      </div>
      <div class="loading-state" v-else>
        <el-icon class="is-loading"><Loading /></el-icon>
        <p>加载中...</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { Search, Loading } from '@element-plus/icons-vue'
import { getActivities } from '@/api/activities'
import { getProducts } from '@/api/products'

// 导入所有本地图片
import banner1 from '@/assets/images/天地龙鳞.jpg'
import banner2 from '@/assets/images/鹊喜桥.jpg'
import banner3 from '@/assets/images/只有你懂.jpg'

// 导入活动图片
import liangzhounian from '@/assets/images/liangzhounian.png'
import activity150W from '@/assets/images/150W.jpg'

// 导入商品图片
import julyDream from '@/assets/images/七月梦境.jpg'
import julyBadge from '@/assets/images/七月吧唧.jpg'
import mousePad from '@/assets/images/鼠标垫.jpg'
import zhaotaiyang from '@/assets/images/赵太阳立牌.jpg'

// 导入默认图片
import defaultActivityImg from '@/assets/images/S1.jpg'
import defaultProductImg from '@/assets/images/S2.jpg'

// 响应式数据
const searchText = ref('')
const activities = ref([])
const products = ref([])
const loading = ref(false)
let requestAbortController = new AbortController()

// 轮播图数据
const banners = ref([
  { id: 1, image: banner1 },
  { id: 2, image: banner2 },
  { id: 3, image: banner3 }
])

// 图片映射表 - 将数据库中的文件名映射到导入的图片对象
const imageMap = {
  // 活动图片
  'liangzhounian.png': liangzhounian,
  '150W.jpg': activity150W,
  
  // 商品图片
  '七月梦境.jpg': julyDream,
  '七月吧唧.jpg': julyBadge,
  '鼠标垫.jpg': mousePad,
  '赵太阳立牌.jpg': zhaotaiyang,
  
  // 默认图片
  'S1.jpg': defaultActivityImg,
  'S2.jpg': defaultProductImg
}

// 获取活动图片
const getActivityImage = (coverImage: string) => {
  if (!coverImage) return defaultActivityImg
  return imageMap[coverImage] || defaultActivityImg
}

// 获取商品图片
const getProductImage = (coverImage: string) => {
  if (!coverImage) return defaultProductImg
  return imageMap[coverImage] || defaultProductImg
}

// 活动状态映射
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'pending': '待发布',
    'published': '预约中', 
    'ongoing': '进行中',
    'completed': '已结束',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'pending': 'info',
    'published': 'warning',
    'ongoing': 'success',
    'completed': 'info',
    'cancelled': 'danger'
  }
  return statusMap[status] || 'info'
}

// 加载数据 - 修改这里过滤商品
const loadData = async () => {
  requestAbortController.abort()
  requestAbortController = new AbortController()
  
  loading.value = true
  try {
    const [activityRes, productRes] = await Promise.all([
      getActivities({ limit: 4 }, { signal: requestAbortController.signal }),
      getProducts({ limit: 8 }, { signal: requestAbortController.signal }) // 多取一些用于过滤
    ])
    
    activities.value = Array.isArray(activityRes.data) ? activityRes.data : []
    
    // 过滤商品：排除音频包和编程课程，只保留周边商品
    if (Array.isArray(productRes.data)) {
      products.value = productRes.data.filter(product => {
        // 排除这两个商品
        const excludeNames = ['樱花治愈ASMR音频包', '银河编程教学课程']
        return !excludeNames.includes(product.name)
      }).slice(0, 4) // 只取前4个
    } else {
      products.value = []
    }
    
    // 调试信息
    console.log('活动数据:', activities.value)
    console.log('过滤后的商品数据:', products.value)
    
  } catch (error) {
    if ((error as Error).name !== 'AbortError') {
      console.error('数据加载失败:', error)
      activities.value = []
      products.value = []
    }
  } finally {
    loading.value = false
  }
}

// 时间格式化
const formatTime = (time: string) => {
  if (!time) return '时间待定'
  return new Date(time).toLocaleDateString('zh-CN')
}

onMounted(() => {
  loadData()
})

onBeforeUnmount(() => {
  requestAbortController.abort()
})
</script>

<style scoped>
/* 样式保持不变 */
.home-page {
  padding: 10px;
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 60px;
  overflow-x: hidden;
}

.search-bar {
  margin-bottom: 15px;
}

.search-input {
  border-radius: 20px;
  --el-input-bg-color: #fff;
}

.banner {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  background: #e0e0e0;
}

.section {
  background: white;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  min-height: 280px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.more {
  color: #409eff;
  font-size: 14px;
  cursor: pointer;
}

.activities-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.activity-card {
  border-radius: 8px;
  overflow: hidden;
  background: white;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  cursor: pointer;
  transition: transform 0.2s ease;
}

.activity-card:hover {
  transform: translateY(-2px);
}

.activity-cover {
  width: 100%;
  height: 120px;
  object-fit: cover;
  background: #f5f5f5;
}

.activity-info {
  padding: 8px;
}

.activity-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #333;
}

.activity-author {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.activity-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

.status-info {
  background: #e6f7ff;
  color: #409eff;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 10px;
}

.status-warning {
  background: #fff7e6;
  color: #e6a23c;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 10px;
}

.status-success {
  background: #f0f9eb;
  color: #67c23a;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 10px;
}

.status-danger {
  background: #fff2f0;
  color: #f56c6c;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 10px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr); /* 明确指定4列 */
  gap: 8px; /* 减小间隙 */
  width: 100%; /* 确保宽度100% */
  margin: 0 auto; /* 居中 */
}

.product-card {
  text-align: center;
  cursor: pointer;
  padding: 6px; /* 减小内边距 */
  border-radius: 8px;
  transition: background 0.2s ease;
  width: 100%; /* 确保宽度100% */
  box-sizing: border-box; /* 包含padding在宽度内 */
}

.product-card:hover {
  background: #fafafa;
}

.product-image {
  width: 100%;
  height: 80px;
  object-fit: cover;
  background: #f5f5f5;
}

.product-info {
  padding-top: 8px;
}

.product-name {
  font-size: 12px;
  margin-bottom: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #333;
}

.product-price {
  font-size: 14px;
  color: #ff4757;
  font-weight: bold;
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 40px 20px;
  color: #999;
  font-size: 14px;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #666;
}
</style>